
# Read control history and apply it.


import numpy as np
import matplotlib.pyplot as plt
from math import pi, sin, cos, sqrt
from random import gauss, uniform, seed
import sys
import csv


Gkp = 0
Gki = 0
Gkd = 0

Gflagopt = True

Glistctrl = []

Gidx = 0

#=============================================================================
Gintegral = 0
Ge0 = 0



#=============================================================================

# For reproducibility purposes
rseed = 123
seed(rseed)


GReagenteTotalAlvo = 1000.0
GReagenteTotal     = 0 
GConcentraEntrada  = 1.0      # gramas por litro
GVolumeEntrada     = 10.0     # litros
GVolumeSaida       = 10.0     # litros
GVolumeReator      = 1000.0   # litros
GTempo             = 0



GReagenteTotalAlvo2 = 1000.0
GReagenteTotal2     = 0 
GConcentraEntrada2  = 1.0      # gramas por litro


GReagenteTotal3     = 0 
GConcentraEntrada3  = 1.0      # gramas por litro


#-----------------------------------------------------------
def Valve():

   global Glistctrl
   global Gidx

   a = float (Glistctrl[Gidx])
   Gidx = Gidx + 1

   return a

#-----------------------------------------------------------
def AtualizarReator():

   global GReagenteTotal
   global GConcentraEntrada
   global GVolumeEntrada
   global GTempo

   global GReagenteTotal2
   global GConcentraEntrada2

   global GReagenteTotal3
   global GConcentraEntrada3

   # Careful, don't call twice.
   valve = Valve ()

   GReagenteTotal = GReagenteTotal + \
                    (valve * 1.0 + 0.0)   * (GVolumeEntrada * GConcentraEntrada) - \
                    (GVolumeSaida * (GReagenteTotal / GVolumeReator)) 

   GReagenteTotal2 = GReagenteTotal2 + \
                    1.0           * (GVolumeEntrada * GConcentraEntrada2) - \
                    (GVolumeSaida * (GReagenteTotal2 / GVolumeReator)) 

   GReagenteTotal3 = GReagenteTotal3 + \
                     (valve * 0.5 + 0.5)   * (GVolumeEntrada * GConcentraEntrada3) - \
                     (GVolumeSaida * (GReagenteTotal3 / GVolumeReator)) 
 
#-----------------------------------------------------------




try:
    arq = open('ctrl.csv', 'r')
    Glistctrl = arq.read().split(',')

except:
    print ("Erro ao abrir arquivo controle")
    sys.exit (-1)


try:
    arq2 = open('Reference.csv', 'r')
    GDados = [float(x) for x in arq2.read().split(',')]

except:
    print ("Erro ao abrir arquivo de dados")
    sys.exit (-1)


# nivel   = CAST model
# nivel 2 = [purely] theoretical
# nivel 3 = blended (= Weigthed)

nivel  = []

nivel2 = []

nivel3 = []

dados = []

# Laço de simulação.
for GTempo in range(0,2000):
   AtualizarReator ()

   nivel .append (GReagenteTotal )
   nivel2.append (GReagenteTotal2)
   nivel3.append (GReagenteTotal3)
   dados .append ([GDados[GTempo],GReagenteTotal,GReagenteTotal3,GReagenteTotal2])


with open('Results.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow (['Target','Simulation', 'Weighted','Theoretical'])
    writer.writerows(dados)



plt.plot (GDados , label='Target', color="blue")
plt.plot (nivel  , label='Simulation', color="green", linestyle = 'dashed')
plt.plot (nivel3 , label='Weigthed', color="#F28C28", linestyle = 'dashed')
plt.plot (nivel2 , label='Theoretical', color="#202020")

plt.legend ()
plt.title  ('Tank Simulation', fontsize=14)
plt.xlabel ('Time', fontsize=14)
plt.ylabel ('Solute concentration', fontsize=14)

plt.ylim((950,1030))

ax = plt.gca()

#ax.set_xlim([xmin, xmax])
ax.set_ylim([950, 1030])
ax.set_xlim([0, 2000])

for item in (\
             #[ax.title,ax.xaxis.label, ax.yaxis.label] + \
             ax.get_xticklabels() + ax.get_yticklabels()):

    item.set_fontsize(12)


plt.grid ()

plt.subplots_adjust(
top=0.88,
bottom=0.12,
left=0.14,
right=0.9,
hspace=0.2,
wspace=0.2
)

ax = plt.gca()
for item in (\
             #[ax.title,ax.xaxis.label, ax.yaxis.label] + \
             ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(14)

for item in ax.get_legend().get_texts():
    item.set_fontsize(14)

plt.draw ()

#plt.savefig('Figure-4b.eps', format='eps')
#plt.savefig('Figure-4b.png', dpi=400)

plt.show ()

#quit()

